package com.lb.shopguide.ui.fragment.guide.recommend;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonArray;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.AdapterRecommendGoods;
import com.lb.shopguide.base.BaseCommonFragment;
import com.lb.shopguide.base.BaseFragment;
import com.lb.shopguide.config.AppConfigManager;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.recommend.RecBannerBean;
import com.lb.shopguide.entity.recommend.RecommendDetailGoodsBean;
import com.lb.shopguide.entity.recommend.RecommendGoodsBean;
import com.lb.shopguide.entity.recommend.ZoneTypeBean;
import com.lb.shopguide.event.guide.StartBrotherEvent;
import com.lb.shopguide.http.method.ApiMethodGuide;
import com.lb.shopguide.ui.activity.ActivityActivityDetail;
import com.lb.shopguide.ui.dialog.DialogShare2Wechat;
import com.lb.shopguide.util.json.JsonUtil;
import com.lb.shopguide.util.lb.AdJumpUtil;
import com.lb.shopguide.util.lb.BizUtil;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Create by kangzhao on 2018/11/18
 * 首页某个type
 */
public class FragmentRecommendGoodsInHome extends BaseCommonFragment {
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_load_more)
    TextView tvLoadMore;

    private AdapterRecommendGoods mAdapterRecommendGoods;
    private List<RecommendGoodsBean> mRecommendGoodsBeanList;

    private ZoneTypeBean curZoneTypeBean;
    private String shareUrl;

    public static FragmentRecommendGoodsInHome newInstance(ZoneTypeBean typeBean) {
        FragmentRecommendGoodsInHome fragmentRecommendGoodsInHome = new FragmentRecommendGoodsInHome();
        Bundle bundle = new Bundle();
        bundle.putSerializable(AppConstant.ZONE_TYPE_BEAN, typeBean);
        fragmentRecommendGoodsInHome.setArguments(bundle);
        return fragmentRecommendGoodsInHome;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_recommend_goods_rv;
    }

    @Override
    public void initData() {
        mRecommendGoodsBeanList = new ArrayList<>();
        Bundle bundle = getArguments();
        if (bundle != null && bundle.containsKey(AppConstant.ZONE_TYPE_BEAN)) {
            curZoneTypeBean = (ZoneTypeBean) bundle.getSerializable(AppConstant.ZONE_TYPE_BEAN);
        }
        assert curZoneTypeBean != null;
        initRequest();
    }

    private void initRequest() {
        if (curZoneTypeBean != null) {
            mRecommendGoodsBeanList = new ArrayList<>();
            getRecommendProductInHome(curZoneTypeBean.getZoneCode());
        }
    }

    @Override
    public void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setNestedScrollingEnabled(false);

        mAdapterRecommendGoods = new AdapterRecommendGoods(R.layout.item_recommend_goods_in_list, mRecommendGoodsBeanList);
        mRecyclerView.setAdapter(mAdapterRecommendGoods);
        initListener();
    }


    private void initListener() {
        mAdapterRecommendGoods.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position < mRecommendGoodsBeanList.size()) {
                    EventBus.getDefault().post(new StartBrotherEvent(FragmentRecGoodsDetail.newInstance(mRecommendGoodsBeanList.get(position).getProductCode())));
                }
            }
        });
        mAdapterRecommendGoods.setOnRecommendGoodsListener(new AdapterRecommendGoods.OnRecommendGoodsListener() {
            @Override
            public void onShareClick(RecommendGoodsBean bean) {
                int orderEntranceCode = -1;
                int productType = -1;
                if (bean.isSecSymbol()) {
                    orderEntranceCode = AppConstant.RECOMMEND_GOODS;
                    productType = AppConstant.PTYPE_RECOMMEND_GOODS;
                } else {
                    orderEntranceCode = AppConstant.COMMON_GOODS;
                    productType = AppConstant.PTYPE_COMMON_GOODS;
                }
                if (AppConfigManager.getAppconfigManager(mContext).getDevMode() == AppConstant.KEY_RUN_MODE_FORMAL) {
                    shareUrl = "https://singlepage.storeer.com/activity_2018/eightHalf_index?productCode=" + bean.getProductCode() + "&appEntranceType=" +
                            AppConstant.APP_ENTRANCE_ANDROID + "&linkStaffCode=" + mUserConfigManager.getUserId() + "&xd_code=XD0001" + "&orderEntryCode=" + orderEntranceCode + "&productType=" +productType;
                } else {
                    shareUrl = "https://sintest.storeer.com/activity_2018/eightHalf_index?productCode=" + bean.getProductCode() + "&appEntranceType=" +
                            AppConstant.APP_ENTRANCE_ANDROID + "&linkStaffCode=" + mUserConfigManager.getUserId() + "&xd_code=XD0001" + "&orderEntryCode=" + orderEntranceCode + "&productType=" + productType;
                }
                DialogShare2Wechat dialogShare2Wechat = DialogShare2Wechat.getDialogShare2Wechat(bean);
                dialogShare2Wechat.show(getFragmentManager(), getPageTag());
                dialogShare2Wechat.setOnDialogClickListener(new DialogShare2Wechat.OnDialogClickListener() {
                    @Override
                    public void onBannerClick(RecBannerBean bean) {
                        dialogShare2Wechat.dismissAllowingStateLoss();
                        jumpLogic(bean);
                    }

                    @Override
                    public void onShareWechat(RecommendGoodsBean recommendGoodsBean) {
                        BizUtil.share(mContext, recommendGoodsBean.getProductName(), recommendGoodsBean.getProductDesc(), shareUrl,
                                recommendGoodsBean.getProductPicUrl(), AppConstant.SHARE_WECHAT);
                    }

                    @Override
                    public void onShareCircle(RecommendGoodsBean recommendGoodsBean) {
                        BizUtil.share(mContext, recommendGoodsBean.getProductName(), recommendGoodsBean.getProductDesc(), shareUrl,
                                recommendGoodsBean.getProductPicUrl(), AppConstant.SHARE_WECHAT_CIRCLE);
                    }

                    @Override
                    public void onShareWechat(RecommendDetailGoodsBean recommendGoodsBean) {

                    }

                    @Override
                    public void onShareCircle(RecommendDetailGoodsBean recommendGoodsBean) {

                    }
                });
            }

            @Override
            public void onCountDownOver(RecommendGoodsBean bean) {
                initRequest();//暂时不做单个刷新
            }
        });
    }

    private void jumpLogic(RecBannerBean bean) {
        BaseFragment fragment = AdJumpUtil.jumpToDestination(bean.getJumpMode(), bean.getPageSdCode(), bean.getRelCode(), bean.getRelName(), bean.getJumpUrl());
        if (fragment instanceof FragmentRecommendHome) {
            pop();
        } else if (fragment instanceof FragmentVirtualActivity) {
            Intent intent = new Intent(getContext(), ActivityActivityDetail.class);
            Bundle bundle = new Bundle();
            bundle.putString(AppConstant.WEB_URL, fragment.getArguments().getString(AppConstant.WEB_URL));
            bundle.putString(AppConstant.WEB_TITLE, fragment.getArguments().getString(AppConstant.WEB_TITLE));
            intent.putExtras(bundle);
            startActivity(intent);
        } else {
            EventBus.getDefault().post(new StartBrotherEvent(fragment));
        }
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        initRequest();
    }

    @Override
    public void finishRefresh() {

    }

    @Override
    public void sessionOutOfDate() {

    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
    }

    @Override
    public String getPageTag() {
        return FragmentRecommendGoodsInHome.class.getCanonicalName();
    }

    @OnClick(R.id.tv_load_more)
    void moreClick() {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentRecommendGoods.newInstance()));
    }

    private void bindEmpty() {
        mRecommendGoodsBeanList.clear();
        mAdapterRecommendGoods.setNewData(mRecommendGoodsBeanList);
    }

    private void getRecommendProductInHome(String zoneCode) {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    JsonArray jsonArray = JsonUtil.getJsonArrayFromMap(response.getReturnContent());
                    for (int i = 0; i < jsonArray.size(); i++) {
                        RecommendGoodsBean bean = JsonUtil.getGson().fromJson(jsonArray.get(i), RecommendGoodsBean.class);
                        mRecommendGoodsBeanList.add(bean);
                    }
                    mAdapterRecommendGoods.setNewData(mRecommendGoodsBeanList);
                } else {
                    bindEmpty();
                }
            }
        };
        ApiMethodGuide.listRecommendProductInHome(zoneCode, new SimpleLbObserver(listener, otherListener), this, FragmentEvent.DESTROY_VIEW);
    }

}
